package com.fy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fy.common.constants.Constants;
import com.fy.common.constants.MessageConstant;

import com.fy.ex.ConditionException;
import com.fy.common.annotation.GlobalInterceptor;
import com.fy.mapper.AdminSysMapper;
import com.fy.mapper.UserMapper;
import com.fy.pojo.entity.AdminSys;
import com.fy.pojo.entity.User;
import com.fy.pojo.vo.user.LoginUserVO;
import com.fy.pojo.vo.user.UserInfoVO;
import com.fy.service.UserService;
import com.fy.utils.PasswordEncrypt;
import com.fy.utils.fileUtils.CreateImageCode;
import com.fy.utils.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@RestController
public class CommonController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminSysMapper adminSysMapper;

    /**
     * 图形验证码生成
     *
     * @param response
     * @param httpSession
     * @param type
     * @throws IOException
     */

    @GetMapping("/checkCode")
    public void checkCode(HttpServletResponse response, HttpSession httpSession, Integer type) throws IOException {
        CreateImageCode vCode = new CreateImageCode(120, 38, 4, 12);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = vCode.getCode();
        String ck = (String) httpSession.getAttribute(Constants.CHECK_CODE);
        String cek = (String) httpSession.getAttribute(Constants.CHECK_CODE_EMAIL);
        AdminSys adminSys = adminSysMapper.selectOne(null);
        if (type == 0) {
            if (!Objects.equals(ck, null)) {
                httpSession.removeAttribute(Constants.CHECK_CODE);
            }
            httpSession.setAttribute(Constants.CHECK_CODE, code);
            httpSession.setMaxInactiveInterval(adminSys.getPicCodeOutTime());
        } else {
            if (!Objects.equals(cek, null)) {
                httpSession.removeAttribute(Constants.CHECK_CODE_EMAIL);
            }
            httpSession.setAttribute(Constants.CHECK_CODE_EMAIL, code);
            httpSession.setMaxInactiveInterval(adminSys.getPicCodeOutTime());
        }
        vCode.write(response.getOutputStream());
        log.info("信息为:{}", response.getOutputStream());
    }

    /***
     * 发送验证码
     *
     * @param httpSession
     * @param email
     * @param checkCode
     * @return
     */
    @PostMapping("/sendEmailCode")
    public Result sendEmailCode(HttpSession httpSession, String email, @RequestParam("checkCode") String checkCode) {
        log.info("ll:{}", httpSession.getAttribute(Constants.CHECK_CODE_EMAIL), checkCode);
        if (checkCode.equalsIgnoreCase((String) httpSession.getAttribute(Constants.CHECK_CODE_EMAIL))) {
            httpSession.removeAttribute(Constants.CHECK_CODE_EMAIL);
            userService.sendEmailCheckCode(email);
            return Result.success();
        } else {
            httpSession.removeAttribute(Constants.CHECK_CODE_EMAIL);
            throw new ConditionException(MessageConstant.GRAPHIC_CAPTCHA_ERROR);
        }
    }

    /**
     * 验证并修改密码
     */
    @PostMapping("/verifyPassword")
    @GlobalInterceptor(checkParams = true)
    public Result verifyPassword(HttpSession session,
            @RequestParam("password") String password) {
        LoginUserVO loginUserVO = (LoginUserVO) session.getAttribute(Constants.SESSION_KEY);
        log.info("修改密码，用户:{}", loginUserVO.getNickName());

        // 使用已有的 MD5 加密工具
        String newMd5Pwd = PasswordEncrypt.getEncryptPassword(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, loginUserVO.getId().intValue());
        User user = userMapper.selectOne(queryWrapper);
        String oldPassword = user.getPassword();
        log.info("旧密码:{}", oldPassword);
        log.info("新密码:{}", newMd5Pwd);
        if (!Objects.equals(newMd5Pwd, oldPassword)) {
            return Result.error("旧密码错误!");
        } else {
            return Result.success();
        }
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/updateUserInfo")
    @GlobalInterceptor
    public Result updateUserInfo(HttpSession session,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String description) {
        LoginUserVO loginUserVO = (LoginUserVO) session.getAttribute(Constants.SESSION_KEY);
        log.info("更新用户信息，用户:{}", loginUserVO.getNickName());
        UserInfoVO userInfo = userService.updateUserInfo(loginUserVO.getId(), username, password, description);
        LoginUserVO lo=new LoginUserVO();
        lo.setId(Long.valueOf(userInfo.getUserId()));
        lo.setNickName(userInfo.getUsername());
        lo.setAvatar(userInfo.getAvatar());
        lo.setAdmin(userInfo.isAdmin());
        session.removeAttribute(Constants.SESSION_KEY);
        session.setAttribute(Constants.SESSION_KEY,lo);
        return Result.success(userInfo);
    }

    /***获取登录信息
     *
     * @param session
     * @return
     */
    @PostMapping("/getLoginUser")
    @GlobalInterceptor
    public Result getLoginUser(HttpSession session) {
        LoginUserVO loginUserVO = (LoginUserVO) session.getAttribute(Constants.SESSION_KEY);
        return Result.success(loginUserVO);
    }
}
